import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 一个端口扫描器，配置machine 和 ports
 */
public class PortScan {

    public static void main(String[] args) throws InterruptedException {

        String machine="web.sanguosha.com";
        int ports=10000;
        List<Integer> ok=new ArrayList<>();

        CountDownLatch countDownLatch=new CountDownLatch(ports);

        for (int i=1;i<=ports;i++){
            new ScanTask(machine,i,countDownLatch,ok).start();

        }
        countDownLatch.await();
        System.out.println("开放端口号"+ok);
    }
}


class ScanTask extends Thread{
    public String machine;
    public int port;
    CountDownLatch countDownLatch;
    List<Integer> ok;

    public ScanTask(String machine, int port, CountDownLatch countDownLatch, List<Integer> ok) {
        this.machine = machine;
        this.port = port;
        this.countDownLatch = countDownLatch;
        this.ok = ok;
    }

    @Override
    public void run() {

        try {
            //如果链接成功就说明端口已经开放，佛则会出错
            System.out.println("正在扫描端口:"+machine+":"+port);
            Socket ss=new Socket(machine,port);
            ok.add(port);
        } catch (IOException e) {
            System.out.println(port+" 未开放");
        }
        countDownLatch.countDown();
    }
}